import { reactive } from 'vue';
import { defineStore } from 'pinia';
import { getAccounts, web3, signMessage } from '../services/web3Service';
import { ApiService } from '../services/api';

export const useEthereumStore = defineStore('ethereum', () => {
    const state = reactive({
        currentAccount: null,
        boundAccount: null,
        isBound: false
    });

    // 检查是否已绑定账户
    async function checkBoundAccount() {
        try {
            const response = await ApiService.get('account/ethereum');
            const { ethereum_address } = response.data;
            state.boundAccount = ethereum_address;
            state.isBound = !!ethereum_address;
            return state.isBound;
        } catch (error) {
            console.error('检查账户绑定状态失败', error);
            return false;
        }
    }

    // 绑定账户
    async function bindAccount(account) {
        try {
            if (!web3) {
                throw new Error('Web3 is not initialized');
            }

            // 获取用户ID
            const response = await ApiService.get('account');
            const userId = response.data.user_id;

            // 生成签名消息，确保没有换行符
            const message = `Bind Ethereum account ${account} to user ${userId}`.trim();
            console.log('Signing message:', message);
            const signature = await signMessage(message, account);
            console.log('Generated signature:', signature);

            await ApiService.post('account/ethereum/bind', { 
                ethereum_address: account,
                signature: signature 
            });
            state.boundAccount = account;
            state.isBound = true;
            return true;
        } catch (error) {
            console.error('绑定账户失败', error);
            throw error;
        }
    }

    // 检查当前账户是否与绑定账户匹配
    async function checkAccountMatch() {
        try {
            const accounts = await getAccounts();
            state.currentAccount = accounts[0];
            return state.currentAccount === state.boundAccount;
        } catch (error) {
            console.error('检查账户匹配失败', error);
            return false;
        }
    }

    // 监听账户变化
    function setupAccountChangeListener() {
        if (window.ethereum) {
            window.ethereum.on('accountsChanged', async (accounts) => {
                state.currentAccount = accounts[0];
                if (state.isBound && state.currentAccount !== state.boundAccount) {
                    // 触发账户不匹配事件
                    window.dispatchEvent(new CustomEvent('ethereumAccountMismatch'));
                }
            });
        }
    }

    return {
        state,
        checkBoundAccount,
        bindAccount,
        checkAccountMatch,
        setupAccountChangeListener
    };
}); 